<#import "/spring.ftl" as spring />
<#import "html-macro.ftl" as h />
<#import "declaration-macro.ftl" as d />
<div class="row">
    <div class="column">
        <button id="returnBtn" class="tiny ui labeled icon button blue">
            <i class="small fa-arrow-left icon"></i>
            返回
        </button>
        <button id="newBtn" class="tiny ui labeled icon button blue">
            <i class="plus icon"></i>
            新增
        </button>
        <button id="saveBtn" class="tiny ui labeled icon button blue">
            <i class="save icon"></i>
            暂存
        </button>
    <#if !d.isInsertPage__>
        <button id="copyBtn" class="tiny ui labeled icon button blue">
            <i class="copy icon"></i>
            复制
        </button>
    </#if>
    <#--<button class="tiny ui labeled icon button blue">-->
    <#--<i class="print icon"></i>-->
    <#--打印-->
    <#--</button>-->
        <button id="submitBtn" class="tiny ui labeled icon button blue allSubmit ">
            <i class="small fa-check icon"></i>
            提交
        </button>
        <button id="useTemplateBtn" class="tiny ui labeled icon button blue">
            <i class="small add circle icon"></i>
            使用模板
        </button>
        <button id="prepareSveAsModel" class="tiny ui labeled icon button blue">
            <i class="small add circle icon"></i>
            另存为模板
        </button>
    <#if d.declarationType__>
        <button id="uploadDeclarationAttachmentBtn" class="tiny ui labeled icon button blue">
            <i class="small add circle icon"></i>
            报关资料上传
        </button>
        <button class="tiny ui labeled icon button blue" id="good_importButton">
            <i class="small add circle icon"></i>
            报关单excel导入
        </button>
        <input type="file" id="hgImportFile" name="file" accept=".xls" style="display:none;"/>
        <a href="<@spring.url "/order/download/excel_export_declaration"/>">下载模板</a>
    </#if>
    </div>
</div>
<!-- 报关单excel导入-->
<#--<script type="text/javascript" src="<@spring.url "/excel/jszip.js"/>"></script>
<script type="text/javascript" src="<@spring.url "/excel/xlsx.js"/>"></script>-->
<script type="text/javascript" src="<@spring.url "/js/require.js"/>"
        data-main="<@spring.url "/js/main.js"/>" defer async="true"></script>
<script>
    $(function () {
        if ($.fn.order.isExport) {
            $(good_importButton).click(function () {
                importBGD();
            });
            $(hgImportFile).change(function () {
                importBGD();
            });
        }

        $(importContainerListButton).click(function () {
            importContainerList();
        });
        $(fileForBox).change(function () {
            importContainerList();
        });
    });
    var X = XLSX;
    function importBGD() {
        var target = event.target;
        var ov = target.textContent;
        target.disabled = true;
        try {
            target.textContent = "Loading...";
        } catch (e) {
        }
        var complete = function () {
            target.disabled = false;
            try {
                target.textContent = ov;
            } catch (e) {
            }
        }
        //兼容相对定位
        var xlsImportSpCfg = {
            "报关单新1": {
                sp0: "特殊关系确认:"
            },
            "装箱（汇总）": {
                sp0: "    TOTAL:"
            }
        }

        var xlsImportCfg = {
            "装箱（汇总）": {
                装箱商品数据: {
                    rowStart: "13", rowEnd: "sp0", rowP: 1, datas: {
                        包装种类: {rowAdd: 0, col: "E"},
                        毛重: {rowAdd: 0, col: "H"},
                        净重: {rowAdd: 0, col: "J"},
                        包装件数: {rowAdd: 0, col: "D"}
                    }
                }
            },
            "报关单新1": {
                收发货人: "A7",
                出口口岸: "F7",
                生产销售单位: "A9",
                运输方式: "F9",
                运输工具名称: "G9",
                监管方式: "F11",
                征免性质: "I11",
                备案号: "L11",
                贸易国: "A13",
                运抵国: "D13",
                指运港: "G13",
                境内货源地: "K13",
                提运单号: "K9",
                许可证号: "A15",
                合同协议号: "A17",
                件数: "D17",
                毛重: "I17",
                净重: "L17",
                备注: "A22",
                成交方式: "D15",
                包装种类: "F17",
                柜号: "A19",
                特殊关系确认: {v: {row: "sp0", col: "C"}},
                价格影响确认: {v: {row: "sp0", col: "F"}},
                支付特许权使用费确认: {v: {row: "sp0", col: "K"}},
                商品数据: {
                    rowStart: "26", rowEnd: "sp0", rowP: 3, datas: {
                        项号: {rowAdd: 0, col: "A"},
                        商品名称: {rowAdd: 0, col: "C"},
                        规格型号: {rowAdd: 2, col: "C"},
                        数量: {rowAdd: 0, col: "F"},
                        单位: {rowAdd: 0, col: "H"},
                        最终目的国: {rowAdd: 0, col: "I"},
                        单价: {rowAdd: 0, col: "K"},
                        总价: {rowAdd: 0, col: "L"},
                        币种: {rowAdd: 0, col: "M"},
                        征免: {rowAdd: 0, col: "N"},
                        商品编号: {rowAdd: 0, col: "B"}
                    }
                }
            }
        }
        if (target.type != 'file' || hgImportFile.files.length <= 0) {
            hgImportFile.click();
            complete.apply();
            return;
        }
        handleFile(hgImportFile, xlsImportCfg, xlsImportSpCfg, complete);
    }
    var importContainerListSpeed = 100;//柜号数据导入速度，其实是导入每行柜号前需等待的毫秒数
    function importContainerList() {
        var target = event.target;
        if (target.tagName == 'I') {
            target = target.parentElement;
        } else {
            target = event.target;
        }
        /*var ov = target.textContent;*/
        var ov = $(target).html();
        target.disabled = true;
        try {
            target.textContent = "Loading...";
        } catch (e) {
        }
        var onComplete = function () {
            target.disabled = false;
            try {
                /*target.textContent = ov;*/
                $(target).html(ov);
            } catch (e) {
            }
        }
        var importDataRow = function (rows, posi) {
            if (posi >= rows.length) {
                onComplete.apply();
                if (posi == 0) {
                    alert("识别到柜号数据[0]行。");
                }
            }
            $.each(rows, function (i, n) {
                var $containersAdd = $(
                        "#containersAdd");
                if (!$containersAdd.is(":hidden")) {
                    $containersAdd.click();
                }
                $("#containerNo").val(n.集装箱号);
                $("#containerWeight").val(n['自重'] == undefined ? '' : n['自重']);
                var $ctSizeDropdown = $(
                        "#containerStandard").parent();
                var ctSize = n.集装箱规格 == "20" ? "S"
                        : "L";
                $ctSizeDropdown.dropdown(
                        "set selected",
                        ctSize);
                $("#containersSave").click();
            });
            onComplete.apply();
        }
        var importDataRow_old = function (rows, posi) {
            var autoConfirmMsg = function () {
                if ($(".messager-window").length > 0) {
                    $(".l-btn-text").click();
                }
            }
            try {
                jzxggselect_123_show.focus();
            } catch (e) {
            }
            try {
                if (posi >= rows.length) {
                    onComplete.apply();
                    if (posi == 0) {
                        alert("识别到柜号数据[0]行。");
                    }
                }
                else {
                    box_jzxh.value = rows[posi]['集装箱号'];
                    autoConfirmMsg.apply();
                    var dtype = rows[posi]['集装箱规格'] == "20" ? "S" : "L";
                    $(".datagrid-row")["S" == dtype ? 0 : 1].click();
                    autoConfirmMsg.apply();
                    box_jzxzz.value = rows[posi]['自重'] == undefined ? "" : rows[posi]['自重'];
                    autoConfirmMsg.apply();
                    box_addButton.click()
                    autoConfirmMsg.apply();
                    setTimeout(function () {
                        importDataRow.call(importDataRow, rows, posi + 1);
                    }, importContainerListSpeed);
                }
            } catch (e) {
                alert("导入失败。" + e);
                onComplete.apply();
            }
        }
        var files = fileForBox.files;
        if (target.type != 'file' || files.length <= 0) {
            fileForBox.click();
            onComplete.apply();
            return;
        }
        var f = files[0];
        var reader = new FileReader();
        var name = f.name;
        reader.onloadstart = function (e) {
            console.log(e.target.result);
        };
        reader.onload = function (e) {
            try {
                var data = e.target.result;
                var wb;
                wb = X.read(data, {type: 'binary'});
                var jarray = X.utils.sheet_to_row_object_array(wb.Sheets[wb.SheetNames[0]]);
                importDataRow(jarray, 0);
                //onComplete.apply();
            } catch (ex) {
                alert("导入失败。" + ex);
                onComplete.apply();
            }
            $("#fileForBox").val("");
        };
        try {
            reader.readAsBinaryString(f);
        } catch (ex) {
            alert("导入失败。" + ex);
            onComplete.apply();
        }
    }
    function process_wb(workbook, xlsImportCfg, xlsImportSpCfg, onComplete) {
        var r = {};
        for (var attr in xlsImportCfg) {
            var icfg = xlsImportCfg[attr];
            var wbs = workbook.Sheets[attr];
            if (wbs) {
                //初始化相对定位数据
                var sp = {}
                var wsp = xlsImportSpCfg[attr];
                if (wsp) {
                    var fsheet = X.utils.sheet_to_formulae(wbs);
                    fsheet.map(function (cell) {
                        for (var attr in wsp) {
                            if (cell.indexOf(wsp[attr]) != -1) {
                                var celladdr = cell.substr(0, cell.indexOf("="));
                                sp[attr] = {col: celladdr.substr(0, 1), row: celladdr.substr(1)};
                            }
                        }
                    });
                }
                for (var iattr in icfg) {
                    var cell = icfg[iattr];
                    if (!isArray(cell)) {
                        if (typeof cell == 'string') {//普通绝对定位
                            var v = wbs[cell];
                            if (v != undefined && v.v != "") {
                                r[iattr] = v.v;
                            }
                        }
                        else {
                            if (Object.keys(cell).length == 1 && cell['v'] != undefined) {//相对定位直接取值
                                try {
                                    var v = wbs[(sp[cell.v.col] ? sp[cell.v.col].col : cell.v.col)
                                                + (sp[cell.v.row] ? sp[cell.v.row].row
                                            : cell.v.row)];
                                } catch (ex) {
                                }
                                if (v && v.v != "") {
                                    r[iattr] = v.v;
                                }
                            }
                            else {//相对定位数组对象取值
                                if (cell['rowStart'] != undefined) {//行拓展
                                    try {
                                        var rowEnd = sp[cell.rowEnd].row - 0;
                                    } catch (ex) {
                                    }
                                    if (rowEnd) {
                                        var rdatas = [];
                                        var dataCfg = cell.datas;
                                        for (var di = (cell.rowStart - 0); di < rowEnd;
                                             di += cell.rowP) {
                                            var d = {};
                                            for (var dattr in dataCfg) {
                                                try {
                                                    var v = wbs[dataCfg[dattr].col + (di
                                                                                      + dataCfg[dattr].rowAdd)];
                                                } catch (ex) {
                                                }
                                                if (v && v.v != "") {
                                                    d[dattr] = v.v;
                                                }
                                            }
                                            if (Object.keys(d).length > 0) {
                                                rdatas.push(d);
                                            }
                                        }
                                        r[iattr] = rdatas;
                                    }
                                }
                                else {//列拓展

                                }
                            }
                        }
                    }
                }
            }
        }
        if (Object.keys(r).length > 0) {
            console.log(r);
            $.get("/order/getExcelModel?dt=${type}&dtt=${d.isGeneralTrade__?string("0",(d.isProcessTrade__?string("1","2")))}&d="
                  + encodeURIComponent(JSON.stringify(r)),
                  function (result) {
                      console.log(result);
                      onComplete.apply();
                      if (result.result) {
                          //location.href = '/order/update?id=';
                      }
                      else {
                          try {
                              alert(JSON.parse(result.msg).msg);
                          } catch (e) {
                              alert(result.msg);
                          }
                      }
                  });
        } else {
            alert("模板内容识别失败。");
            onComplete.apply();
        }
    }
    function isArray(o) {
        return Object.prototype.toString.call(o) === '[object Array]';
    }
    function handleFile(fileInput, cfg, xlsImportSpCfg, onComplete) {
        var files = fileInput.files;
        if (files.length == 0) {
            alert("请选择文件。");
            onComplete.apply();
            return;
        }
        var f = files[0];

        var reader = new FileReader();
        var name = f.name;
        reader.onload = function (e) {
            try {
                var data = e.target.result;
                var wb;
                wb = X.read(data, {type: 'binary'});
                process_wb(wb, cfg, xlsImportSpCfg, onComplete);
            } catch (ex) {
                alert("导入失败。" + ex);
                onComplete.apply();
            }

        };
        try {
            reader.readAsBinaryString(f);
        } catch (ex) {
            alert("导入失败。" + ex);
            onComplete.apply();
        }
    }
</script>

<script type="text/javascript">
    /**
     * 说明从什么页面进入此页面，目前只在客户驳回列表中使用
     */
    var validationRules = {
        declarationFormRule: {
            fields: {
                company_co: {
                    identifier: 'company_co',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '收发货人为必填项'
                        }
                    ]
                },
                fahuo_company_co: {
                    identifier: 'fahuo_company_co',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '消费使用单位为必填项'
                        }
                    ]
                },
                shenbao_company_co: {
                    identifier: 'shenbao_company_co',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '申报单位为必填项'
                        }
                    ]
                },
                /*tex_company: {
                    identifier: 'tex_company',
                    rules: [
                        {
                            type: 'empty'
                        }
                    ]
                },*/
                trade_mode_code: {
                    identifier: 'trade_mode_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '监管方式为必填项'
                        }
                    ]
                },
                levymode_code: {
                    identifier: 'levymode_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '征免性质为必填项'
                        }
                    ]
                },
                arrived_country_code: {
                    identifier: 'arrived_country_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '运抵国为必填项'
                        }
                    ]
                },
                trading_country_code: {
                    identifier: 'trading_country_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '贸易国为必填项'
                        }
                    ]
                },
                arrived_port_code: {
                    identifier: 'arrived_port_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '指运港为必填项'
                        }
                    ]
                },
                /**
                 goods_addr_code: {
                    identifier: 'goods_addr_code',
                    rules: [{
                        type: 'empty'
                    }]
                },
                 */
                goods_count: {
                    identifier: 'goods_count',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '件数为必填项'
                        },
                        {
                            type: 'regExp[/^[1-9][0-9]{0,8}$|^0{1,9}$/]',
                            prompt: '件数格式错误，允许最大值999999999'
                        }
                    ]
                },
                goods_package_code: {
                    identifier: 'goods_package_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '包装种类为必填项'
                        }
                    ]
                },
                gross_weight: {
                    identifier: 'gross_weight',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '毛重为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '毛重格式错误保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '毛重的最大值为999999999'
                        }
                    ]
                },
                net_weight: {
                    identifier: 'net_weight',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '净重为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '净重格式错误，保留1-5位小数'
                        },
                        {
                            type: 'lessThan[gross_weight]',
                            prompt: '请输入小于等于毛重'
                        },
                        {
                            type: 'equal[total-net-weight]',
                            prompt: '总净重要等于净重总汇'
                        }
                    ]
                },
                deal_mode_code: {
                    identifier: 'deal_mode_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '成交方式为必填项'
                        }
                    ]
                },
                record_id: {
                    identifier: 'record_id',
                    optional: 'true',
                    rules: [
                        {
                            type: 'exactLength[12]',
                            prompt: '备案号输入长度必须为12'
                        }
                    ]
                },
                contract_no: {
                    identifier: 'contract_no',
                    optional: 'true',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '合同协议号必须填写'
                        }, {
                            type: 'maxLength[20]',
                            prompt: '合同协议号允许最大长度20'
                        }
                    ]
                },
                transport_na: {
                    identifier: 'transport_na',
                    rules: [
                        {
                            type: 'maxLength[26]',
                            prompt: '运输工具名称允许最大长度26'
                        }
                    ]
                },
                voyage_no: {
                    identifier: 'voyage_no',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[25]',
                            prompt: '航次号允许最大长度25'
                        }
                    ]
                },
                bl_no: {
                    identifier: 'bl_no',
                    rules: [
                        {
                            type: 'maxLength[16]',
                            prompt: '提运单号允许最大长度16'
                        }
                    ]
                },
                license_no: {
                    identifier: 'license_no',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[20]',
                            prompt: '许可证号允许最大长度20'
                        }
                    ]
                },
                freight2: {
                    identifier: 'freight2',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^0(\.[0-9]{1,7})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,7})?$/]',
                            prompt: '运费值格式错误，保留1-7位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '运费值允许最大值999999999'
                        }
                    ]
                },
                premium2: {
                    identifier: 'premium2',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^0(\.[0-9]{1,7})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,7})?$/]',
                            prompt: '保费值格式错误，保留1-7位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '保费值允许最大值999999999'
                        }
                    ]
                },
                otherfee2: {
                    identifier: 'otherfee2',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^0(\.[0-9]{1,7})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,7})?$/]',
                            prompt: '杂费值格式错误，保留1-7位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '杂费值允许最大值999999999'
                        }
                    ]
                },
                remark: {
                    identifier: 'remark',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[255]',
                            prompt: '最大长度255'
                        }
                    ]
                },
                buyer: {
                    identifier: 'buyer',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '买方为必填项'
                        }
                    ]
                }
            },
            inline: true
        },
        goodsFormRule: {
            fields: {
                index_num: {
                    identifier: 'index_num',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '商品序号为必填项'
                        },
                        {
                            type: 'number',
                            prompt: '商品序号格式错误'
                        }
                    ]
                },
                code_t: {
                    identifier: 'code_t',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '商品编号为必填项'

                        }
                    ]
                },
                name: {
                    identifier: 'name',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '商品名称为必填项'
                        },
                        {
                            type: 'maxLength[32]',
                            prompt: '商品名称允许最大长度32'
                        }
                    ]
                },
                goods_mode: {
                    identifier: 'goods_mode',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[255]',
                            prompt: '规格型号允许最大长度255'
                        }
                    ]
                },
                count: {
                    identifier: 'count',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '计价数量为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '计价数量格式错误，保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '计价数量允许最大值999999999'
                        }
                    ]
                },
                unitCode: {
                    identifier: 'unitCode',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '计价单位为必填项'
                        }
                    ]
                },
                total_price: {
                    identifier: 'total_price',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '总价为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,2})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,2})?$/]',
                            prompt: '总价格式错误，保留1-2位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '总价允许最大值999999999'
                        }
                    ]
                },
                unit_price: {
                    identifier: 'unit_price',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '单价为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,4})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,4})?$/]',
                            prompt: '单价格式错误，保留1-4位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '单价允许最大值999999999'
                        }
                    ]
                },
                currencyCode: {
                    identifier: 'currencyCode',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '币制为必填项'
                        }
                    ]
                },
                legal_count: {
                    identifier: 'legal_count',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '法定数量为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '法定数量格式错误，保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '法定数量允许最大值999999999'
                        }
                    ]
                },
                legalUnitCode: {
                    identifier: 'legalUnitCode',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '法定单位为必填项'
                        }
                    ]
                },
                destination_code: {
                    identifier: 'destination_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '目的国为必填项'
                        }
                    ]
                },
                origin_country_code: {
                    identifier: 'origin_country_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '原产国为必填项'
                        }
                    ]
                },
                levyModeCode: {
                    identifier: 'levyModeCode',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '征免为必填项'
                        }
                    ]
                },
                second_count: {
                    identifier: 'second_count',
                    optional: true,
                    rules: [
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '第二数量格式错误，保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '第二数量允许最大值999999999'
                        }
                    ]
                },
                version_no: {
                    identifier: 'version_no',
                    optional: true,
                    rules: [
                        {
                            type: 'maxLength[8]',
                            prompt: '版本号允许最大长度8'
                        }
                    ]
                },
                goods_no: {
                    identifier: 'goods_no',
                    optional: true,
                    rules: [
                        {
                            type: 'maxLength[32]',
                            prompt: '货号允许最大长度32'
                        }
                    ]
                },
                /*processing_fee: {
                    identifier: 'processing_fee',
                    rules: [
                        {
                            type: 'empty'
                        }
                    ]
                },*/
                package_type: {
                    identifier: 'package_type',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '包装种类为必填项'
                        }
                    ]
                },
                goods_gross_weight: {
                    identifier: 'goods_gross_weight',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '毛重为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '毛重格式错误，保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '毛重允许最大值999999999'
                        }
                    ]
                },
                goods_net_weight: {
                    identifier: 'goods_net_weight',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '净重为必填项'
                        },
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '净重格式错误，保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '净重允许最大值999999999'
                        },
                        {
                            type: 'lessThan[goods_gross_weight]',
                            prompt: '净重要小于等于毛重'
                        }
                    ]
                },
                /*boxMark: {
                    identifier: 'boxMark',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '箱唛为必填项'
                        },
                        {
                            type: 'maxLength[255]',
                            prompt: '箱唛允许最大长度255'
                        }
                    ]
                },*/
                goods_number: {
                    identifier: 'goods_number',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '包装件数为必填项'
                        },
                        {
                            type: 'regExp[/^[1-9][0-9]{0,8}$|^0{1,9}$/]',
                            prompt: '包装件数允许最大值999999999'
                        }
                    ]
                },
                packinglist_remark: {
                    identifier: 'packinglist_remark',
                    optional: true,
                    rules: [
                        {
                            type: 'maxLength[255]',
                            prompt: '装箱单备注内容允许最大长度255'
                        }
                    ]
                }
            },
            inline: true
        },
        allFormFormatRule: {
            fields: {
                record_id: {
                    identifier: 'record_id',
                    optional: 'true',
                    rules: [
                        {
                            type: 'exactLength[12]',
                            prompt: '备案号输入长度必须为12'
                        }
                    ]
                },
                contract_no: {
                    identifier: 'contract_no',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[20]',
                            prompt: '合同协议号允许最大长度20'
                        }
                    ]
                },
                transport_na: {
                    identifier: 'transport_na',
                    rules: [
                        {
                            type: 'maxLength[26]',
                            prompt: '运输工具名称允许最大长度26'
                        }
                    ]
                },
                voyage_no: {
                    identifier: 'voyage_no',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[25]',
                            prompt: '航次号允许最大长度25'
                        }
                    ]
                },
                bl_no: {
                    identifier: 'bl_no',
                    rules: [
                        {
                            type: 'maxLength[16]',
                            prompt: '提运单号允许最大长度16'
                        }
                    ]
                },
                license_no: {
                    identifier: 'license_no',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[20]',
                            prompt: '许可证号最大长度20'
                        }
                    ]
                },
                goods_count: {
                    identifier: 'goods_count',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^[1-9][0-9]{0,8}$|^0{1,9}$/]',
                            prompt: '件数格式错误，允许最大值999999999'
                        }
                    ]
                },
                freight2: {
                    identifier: 'freight2',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^0(\.[0-9]{1,7})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,7})?$/]',
                            prompt: '运费值格式错误，保留1-7位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '运费值允许最大值999999999'
                        }
                    ]
                },
                gross_weight: {
                    identifier: 'gross_weight',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '毛重格式错误，保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '毛重允许最大值999999999'
                        }
                    ]
                },
                net_weight: {
                    identifier: 'net_weight',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^0(\.[0-9]{1,5})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,5})?$/]',
                            prompt: '毛重格式错误，保留1-5位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '毛重允许最大值999999999'
                        },
                        {
                            type: 'lessThan[gross_weight]',
                            prompt: '请输入小于等于毛重'
                        },
                        {
                            type: 'equal[total-net-weight]',
                            prompt: '总净重要等于净重总汇'
                        }
                    ]
                },
                premium2: {
                    identifier: 'premium2',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^0(\.[0-9]{1,7})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,7})?$/]',
                            prompt: '保费值格式错误，保留1-7位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '保费值允许最大值999999999'
                        }
                    ]
                },
                otherfee2: {
                    identifier: 'otherfee2',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^0(\.[0-9]{1,7})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,7})?$/]',
                            prompt: '杂费值格式错误，保留1-7位小数'
                        },
                        {
                            type: 'maxValue[999999999]',
                            prompt: '杂费值允许最大值999999999'
                        }
                    ]
                },
                remark: {
                    identifier: 'remark',
                    optional: 'true',
                    rules: [
                        {
                            type: 'maxLength[255]',
                            prompt: '备注允许最大长度255'
                        }
                    ]
                }
            },
            inline: true
        },
        topFormRule: {
            fields: {
                id: {
                    identifier: 'supCompany.id',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '报关行为必填项'
                        }
                    ]
                },
                export_port_code: {
                    identifier: 'export_port_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '出口口岸为必填项'
                        }
                    ]
                },

                declaration_port_code: {
                    identifier: 'declaration_port_code',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '申报口岸为必填项'
                        }
                    ]
                }
            },
            inline: true
        },
        otherFormRule: {
            fields: {
                special_relationship_confirm: {
                    identifier: 'special_relationship_confirm',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '特殊关系确认为必填项'
                        }
                    ]
                },
                price_impact_confirm: {
                    identifier: 'price_impact_confirm',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '价格影响确认为必填项'
                        }
                    ]
                },
                payment_royaltils_confirm: {
                    identifier: 'payment_royaltils_confirm',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '支付特许权使用费确认为必填项'
                        }
                    ]
                }
            },
            inline: true
        },
        declaContainersFormRule: {
            fields: {
                containerNo: {
                    identifier: 'containerNo',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '集装箱号为必填项'
                        },
                        {
                            type: 'regExp[/^[A-Z]{4}[0-9]{7}$/]',
                            prompt: '以四位大写字符开头后加7个数字'
                        }
                    ]
                },
                containerStandard: {
                    identifier: 'containerStandard',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '集装规格为必填项'
                        }
                    ]
                },
                containerWeight: {
                    identifier: 'containerWeight',
                    optional: 'true',
                    rules: [
                        {
                            type: 'regExp[/^[1-9][0-9]{0,8}$|^0{1,9}$/]',
                            prompt: '自重允许最大值999999999'
                        }
                    ]
                }

            },
            inline: true
        },
        suiFuDansFormRules: {
            fields: {
                suifudan_co: {
                    identifier: 'suifudan_co',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '单证代码为必填项'
                        }
                    ]
                },
                suifudan_no: {
                    identifier: 'suifudan_no',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '单证编号为必填项'
                        },
                        {
                            type: 'maxLength[32]',
                            prompt: '单证编号最大长度32'
                        }
                    ]
                }
            },
            inline: true
        },
        extendExportDeclarationFormRule: {
            fields: {
                invoice_no: {
                    identifier: 'invoice_no',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '发票号不能为空'
                        }
                    ]
                },
                contract_no: {
                    identifier: 'contract_no',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '合同协议号不能为空'
                        }
                    ]
                },
                goods_addr: {
                    identifier: 'goods_addr',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '境内货源地不能为空'
                        }
                    ]
                }
            }
        },
        extendGeneralGoodsFormRule: {
            fields: {
                goods_mode: {
                    identifier: 'goods_mode',
                    rules: [
                        {
                            type: 'empty',
                            prompt: '要素为必填项'
                        }
                    ]
                }
            }
        }
    };
    var showError;
    var layerIndex;
    /**
     * 说明从什么页面进入此页面，目前只在客户驳回列表中使用
     */
    var prev_page = "${RequestParameters['prev_page']!}";
    var needAddProcessFee = function () {
        var processFreeRule = {
            identifier: 'processing_fee',
            rules: [
                {
                    type: 'empty',
                    prompt: '工缴费为必填项'
                }
            ]
        };
        if ($.fn.order.isExport) {
            if ($.fn.order.isProcessTrade) {
                if ($("#processing_fee").parent().css("display") == "block") {
                    validationRules.goodsFormRule.fields['processing_fee'] = processFreeRule;
                } else {
                    if (validationRules.goodsFormRule.fields['processing_fee']) {
                        delete validationRules.goodsFormRule.fields['processing_fee'];
                    }
                }
            }
        }
    };
    $(document).ready(function () {
        $("#returnBtn").click(function () {
            if (prev_page && prev_page == 'customerReject') {
                location.href = "<@spring.url "/business/rejectMain"/>";
            } else {
                location.href = "<@spring.url "/business/unpaidMain"/>";
            }
        });
        //新增按钮
        $("#newBtn").click(function () {
        <#if d.declarationType__>
            location.href =
            "<@spring.url "/order/out/"+((declaration.tradeType=='0')?string('general','process')) />";
        <#else>
            location.href =
            "<@spring.url "/order/in/"+((declaration.tradeType=='0')?string('general',((declaration.tradeType=='1')?string('process','special')))) />";
        </#if>
        });
        showError = function (errores) {
            if (errores.length == 0) {
                return;
            }
            var $error = $("#errorMsg");
            var errorStr = "";
            $.each(errores, function (i, n) {
                errorStr += "<li class='errorList'>" + n + "</li>";
            });
            $error.html(errorStr);
            $error.show().delay(3000).hide(0, function () {
                $(this).empty();
            });
        };
        //验证前还需要一些准备
        if ($.fn.order.isExport) {
            var __fields = $.extend({}, validationRules.declarationFormRule.fields,
                                    validationRules.extendExportDeclarationFormRule.fields);
            validationRules.declarationFormRule.fields = __fields;
            if ($.fn.order.isGeneralTrade) {
                var _generalTradeFields = $.extend({}, validationRules.goodsFormRule.fields,
                                                   validationRules.extendGeneralGoodsFormRule.fields);
                validationRules.goodsFormRule.fields = _generalTradeFields;
            }
            needAddProcessFee();
        }
        //提交
        beforeSubmitValidate = function () {
            $('.ui.allform').form(validationRules.declarationFormRule);
            $(".ui.topform").form(validationRules.topFormRule);
            $(".ui.otherForm").form(validationRules.otherFormRule);
            var topSubmitValid = $(".ui.topform").form("is valid");
            var allSubmitValid = $('.ui.allform').form('is valid');
            var otherSubmitValid = $('.ui.otherForm').form('is valid');
            var goodsFormLen = $("#commodities").nextAll("table").find("tbody tr").length;
            var declaContainersLen = $("#declaContainers").nextAll("table").find("tbody tr").length;
            var errorMsges = [];
            if (topSubmitValid && allSubmitValid && otherSubmitValid && goodsFormLen) {
                if (declaContainersLen != 0) {
                    var cabinetNo = [];
                    var json = {};
                    $.each($("#declaContainers").nextAll("table").find("tbody tr"),
                           function (i, n) {
                               var cabinetNoVal = $(n).find("td").eq(0).text();
                               cabinetNo.push(cabinetNoVal);
                           });
                    for (var i = 0; i < cabinetNo.length; i++) {
                        if (!json[cabinetNo[i]]) {
                            json[cabinetNo[i]] = 1;
                        } else {
                            errorMsges.push("重复获取柜号!");
                            break;
                        }
                    }
                } else {
                    return true;
                }
            } else {
                if (!(topSubmitValid && allSubmitValid && otherSubmitValid && goodsFormLen)) {
                    layer.close(layerIndex);
                    $("#submitBtn").removeDisabledClass();
                    return false;
                }
                if (goodsFormLen == 0) {
                    errorMsges.push("没有商品信息!");
                }
            }
            if (errorMsges.length != 0) {
                layer.close(layerIndex);
                showError(errorMsges);
                $("#submitBtn").removeDisabledClass();
                return false;
            }
        };
        var $form = $("#declarationForm");
        $("#submitBtn").click(function () {
            $form.unbind('submit');
            $(this).addDisabledClass();
            $form.submit(function () {
                var __url = '<@spring.url "/order/submit" />';
                if (prev_page && prev_page == 'customerReject') {
                    __url = '<@spring.url "/order/customerRejectSubmit" />';
                }
                $(this).append($("input").filter(function () {
                    var name = $(this).attr("name");
                    return !(name == undefined || name == "" || /^0.+/.test(name));
                }).clone());
                $(this).ajaxSubmit(
                        {
                            type: 'post', // 提交方式 get/post
                            url: __url, // 需要提交的 url
                            beforeSubmit: beforeSubmitValidate,
                            success: function (data) { // data 保存提交后返回的数据，一般为 json 数据
                                // 此处可对 data 作相关处理
                                console.log(data);
                                var tipMsg;
                                if (data.result == true) {
                                    tipMsg = data.msg;
                                    layer.alert(tipMsg, function (index) {
                                        layer.close(index);
                                        location.href =
                                        "<@spring.url "/order/payPage?id="/>" + data.data;
                                    });
                                } else {
                                    tipMsg = data.msg + "<br/>错误原因：" + data.data;
                                    layer.alert(tipMsg);
                                }
                                $("#submitBtn").removeDisabledClass();
                            }
                        });
                $form.empty();
                return false;
            });
            if ($("#declaContainers").nextAll("table").find("tbody tr").length == 0) {
                layerIndex = layer.confirm('系统检测到您没有录入柜号，请确认是否为散货？', {
                    btn: ['是', '否']
                }, function () {
                    $form.submit();
                }, function () {
                    doShowForm(true, $("#containersAdd"), $("#containersSave"),
                               $("#containersCancle"),
                               $("#declaContainers"));
                    $("#containerNo").focus();
                    $("#submitBtn").removeDisabledClass();
                });
            } else {
                $form.submit();
            }

            /*$form.submit();*/
        });
        //使用模板
        $("#useTemplateBtn").click(function () {
            loadBizFromHistoryOperation();
        });
        function generateUUID() {
            var d = new Date().getTime();
            var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = (d + Math.random() * 16) % 16 | 0;
                d = Math.floor(d / 16);
                return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
            });
            return uuid;
        };
        //查看编辑报关单资料
        var bill_no = '${declaration.id}';
        $("#uploadDeclarationAttachmentBtn").click(function () {
            if (bill_no == '') {
                bill_no = generateUUID();
                $("input[name='tempAttachmentBillNo']").val(bill_no);
            }
            layer.open({
                           type: 2,
                           offset: ['5%', '12%'],
                           content: '/business/uploadMain?type=declaration#' + bill_no,
                           area: ['815px', '620px']
                       });
        });
        //另存为模板
        $("#prepareSveAsModel").click(function () {
            prepareSveAsModel();
        });
    });
    /**
     *从历史业务数据载入模版，页面导航
     *bizType = [all, booking, trail, declaration]
     */
    function loadBizFromHistory() {
//        layer.confirm("检测到当前页面有未保存的业务数据，是否继续操作，点击确认将覆盖当前数据?", function () {
//            loadBizFromHistoryOperation(bizType);
//        }, function () {
//            return;
//        });
        loadBizFromHistoryOperation();
    }
    /**
     *从历史业务数据载入模版，真实操作
     *bizType = [all, booking, trail, declaration]
     */
    function loadBizFromHistoryOperation() {
        layer.open({
                       type: 2,
                       offset: ['5%', '12%'],
                       content: '/business/model-main?type=D&dType=${type}',
                       area: ['815px', '620px']
                   });
    }
    /**
     * 另存为模板
     */
    function prepareSveAsModel() {
        layer.open({
                       type: 2,
                       content: "/business/prepareSveAsModel",
                       area: ['600px', '300px']
                   });
    }

    /**
     * 保存为模板，现由子页面进行调用
     * @param modelName 模板名称
     * @param modelType 模板类型
     */
    function saveAsModel(modelName, modelType) {
        var $inputs = $("input").filter(function () {
            var name = $(this).attr("name");
            return !(name == undefined || name == "" || /^0.+/.test(name));
        });
        var data = {};
        $.each($inputs, function (i, n) {
            data[n.name] = n.value;
        });
        if (data.length == 0) {
            alert("保存失败，请刷新页面后重试");
            return;
        }
        data.modelName = modelName;
        data.modelType = modelType;
        layer.load(2, {shade: [0.2]});
        $.ajax({
                   url: '<@spring.url "/business/saveAsModel"/>',
                   data: data,
                   method: 'POST',
                   dataType: 'json',
                   success: function (result) {
                       layer.closeAll();
                       result = $.parseJSON(result);
                       if (result.rs) {
                           layer.alert("保存成功");
                       } else {
                           layer.alert("发生了错误，CODE[" + result.code + "]");
                       }
                   },
                   error: function () {
                       layer.closeAll();
                       layer.alert("发生了错误，CODE[001]");
                   }
               });
    }
</script>